package com.szewec.ps.ui.road.facilities.investigation.task;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivityRoadSlowLaneBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTask;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTaskDTO;
import com.szewec.ps.model.road.facilities.investigation.task.RoadSlowLane;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;

import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class RoadSlowLaneActivity extends BaseMediaPickerActivity {
    private ActivityRoadSlowLaneBinding binding;

    /********字典start***********/
    // 人非分隔形式
    private ArrayList<String> separateTypeDict = new ArrayList<>();
    // 慢行道铺面类型
    private ArrayList<String> slowLanePavementTypeDict = new ArrayList<>();
    // 人行道铺面类型
    private ArrayList<String> sidewalkPavementTypeDict = new ArrayList<>();
    // 非机动车道铺面类型
    private ArrayList<String> bicycleLanePavementTypeDict = new ArrayList<>();
    /********字典end***********/
    private String modeFlag; // 用于区分新增还是修改还是详情展示
    private ViewModeValue viewModeValue;
    // 慢行道ID
    private String slowLaneId;
    // 慢行道对象
    private RoadSlowLane roadSlowLane = new RoadSlowLane();
    // 路段设施调查任务DTO
    private RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO roadFacilitiesTaskDTO;

    // 照片上传数组
    private List<String> photoSketchUploadIdArr = new ArrayList<>();
    // 照片文件数组
    private ArrayList<MediaFile> photoSketchFileArr = new ArrayList<>();
    // 图片适配器
    private CustomPickerAdapterShowAndEdit photoSketchAdapter;
    // 移除的图片ID数组
    private List<String> deletePhotoIdArr = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_road_slow_lane);
        ButterKnife.bind(this);
        initData();
        initView();
        initTitleBar();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 初始化字典
        separateTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.separateType)));
        slowLanePavementTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.pavementType)));
        sidewalkPavementTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.pavementType)));
        bicycleLanePavementTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.pavementType)));

        // 获取intent中的数据
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue =
                (PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO>) getIntent().getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        roadFacilitiesTaskDTO = presentValue.getT();
        Log.i("慢行道getData", JSONObject.toJSONString(roadFacilitiesTaskDTO));
    }

    /**
     * 初始化界面样式
     */
    private void initView() {
        viewModeValue = new ViewModeValue(this, modeFlag, binding.titleBar, binding.llContainer);

        // 初始化照片适配器
        photoSketchAdapter = initTypeMediaRecyclerView(photoSketchUploadIdArr, photoSketchFileArr,
                binding.photoSketchSketchRV, true, false, true, deletePhotoIdArr);

        roadSlowLane = roadFacilitiesTaskDTO.getRoadSlowLane() == null ? new RoadSlowLane() : roadFacilitiesTaskDTO.getRoadSlowLane();
        // 人非分隔形式
        Integer separateType = roadSlowLane.getSeparateType() == null ? 1 : roadSlowLane.getSeparateType();
        // 慢行道宽度
        BigDecimal slowLaneWidth = roadSlowLane.getSlowLaneWidth() == null ? new BigDecimal("2.5") : roadSlowLane.getSlowLaneWidth();
        // 慢行道铺面类型
        Integer slowLanePavementType = roadSlowLane.getSlowLanePavementType() == null ? 1 : roadSlowLane.getSlowLanePavementType();
        // 人行道宽度
        BigDecimal sidewalkWidth = roadSlowLane.getSidewalkWidth() == null ? new BigDecimal("2.5") : roadSlowLane.getSidewalkWidth();
        // 人行道铺面类型
        Integer sidewalkPavementType = roadSlowLane.getSidewalkPavementType() == null ? 1 : roadSlowLane.getSidewalkPavementType();
        // 非机动车道宽度
        BigDecimal bicycleLaneWidth = roadSlowLane.getBicycleLaneWidth() == null ? new BigDecimal("2.5") : roadSlowLane.getBicycleLaneWidth();
        // 非机动车道铺面类型
        Integer bicycleLanePavementType = roadSlowLane.getBicycleLanePavementType() == null ? 1 : roadSlowLane.getBicycleLanePavementType();
        // 分隔带宽度
        BigDecimal separateTypeWidth = roadSlowLane.getSeparateTypeWidth() == null ? new BigDecimal("1.5") : roadSlowLane.getSeparateTypeWidth();

        // 获取慢行道ID
        slowLaneId = roadSlowLane.getId();

        binding.slowLaneWidth.setValue(slowLaneWidth);
        binding.slowLanePavementType.setValue(Enums.PavementTypeEnum.getValueByKey(slowLanePavementType));
        binding.sidewalkWidth.setValue(sidewalkWidth);
        binding.sidewalkPavementType.setValue(Enums.PavementTypeEnum.getValueByKey(sidewalkPavementType));
        binding.bicycleLaneWidth.setValue(bicycleLaneWidth);
        binding.bicycleLanePavementType.setValue(Enums.PavementTypeEnum.getValueByKey(bicycleLanePavementType));
        binding.separateTypeWidth.setValue(separateTypeWidth);
        showVIew(Enums.SeparateTypeEnum.getValueByKey(separateType));
        // 显示附件内容
        initViewFile();
    }

    // 设置照片
    private void initViewFile() {
        // 先根据fileId查询附件数据
        if (!CollectionUtils.isEmpty(roadSlowLane.getAddIds())) {
            requestFilesByIds(roadSlowLane.getAddIds(), this::initAdapterData);
        }
        // 根据业务ID查询附件信息
        else if (StringUtils.isNotEmpty(roadSlowLane.getId())) {
            requestFiles(FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_SLOW_LANE_FILE_BIZ_TYPE, roadSlowLane.getId(), this::initAdapterData);
        }
    }

    // 往照片适配器里面设置图片显示
    private void initAdapterData(List<MediaFile> mediaFileList) {
        if (CollectionUtils.isEmpty(mediaFileList)) {
            return;
        }
        photoSketchUploadIdArr.clear();
        photoSketchFileArr.clear();
        // 添加到文件数组
        photoSketchFileArr.addAll(mediaFileList);
        for (MediaFile mediaFile : photoSketchFileArr) {
            photoSketchUploadIdArr.add(mediaFile.getId());
        }
        // 设置适配器数据源
        photoSketchAdapter.setmMediaFileList(mediaFileList);
    }

    private void initTitleBar() {
        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(modeFlag)
                || Constants.PRESENT_VALUE_FLAG.EDIT.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::appendOrModifyData);
        }
    }

    /**
     * 保存数据
     */
    private void appendOrModifyData() {
        setParamData();
        roadFacilitiesTaskDTO.setRoadSlowLane(roadSlowLane);
        Log.i("慢行道app", JSONObject.toJSONString(roadFacilitiesTaskDTO));
        Intent intent = new Intent();
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(modeFlag, roadFacilitiesTaskDTO);
        intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
        setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
        finish();
    }

    /**
     * 组装参数
     */
    private void setParamData() {
        // 保存时需要先清空之前设置的默认值
        roadSlowLane = new RoadSlowLane();

        // 添加路段调查任务ID
        RoadFacilitiesInvestigationTask facilitiesInvestigationTask = roadFacilitiesTaskDTO.getFacilitiesInvestigationTask();
        if (facilitiesInvestigationTask != null && StringUtils.isNotEmpty(facilitiesInvestigationTask.getId())) {
            roadSlowLane.setRoadInvestigationTaskId(facilitiesInvestigationTask.getId());
        }
        roadSlowLane.setId(slowLaneId);
        roadSlowLane.setRemoveIds(deletePhotoIdArr);
        roadSlowLane.setAddIds(photoSketchUploadIdArr);
        // 根据人非分隔形式 决定存储哪些数据
        String separateType = binding.separateType.getStringValue();
        roadSlowLane.setSeparateType(Enums.SeparateTypeEnum.getKeyByValue(separateType));
        // 人非分隔
        if (Enums.SeparateTypeEnum.PEOPLE_NOT_MIXED.getValue().equals(separateType)) {
            roadSlowLane.setSlowLaneWidth(binding.slowLaneWidth.getBigDecimalValue());
            roadSlowLane.setSlowLanePavementType(Enums.PavementTypeEnum.getKeyByValue(binding.slowLanePavementType.getStringValue()));
        }
        // 标线隔离
        else if (Enums.SeparateTypeEnum.MARKING_ISOLATION.getValue().equals(separateType)) {
            roadSlowLane.setSidewalkWidth(binding.sidewalkWidth.getBigDecimalValue());
            roadSlowLane.setSidewalkPavementType(Enums.PavementTypeEnum.getKeyByValue(binding.sidewalkPavementType.getStringValue()));
            roadSlowLane.setBicycleLaneWidth(binding.bicycleLaneWidth.getBigDecimalValue());
            roadSlowLane.setBicycleLanePavementType(Enums.PavementTypeEnum.getKeyByValue(binding.bicycleLanePavementType.getStringValue()));
        }
        // 物理隔离
        else if (Enums.SeparateTypeEnum.PHYSICAL_ISOLATION.getValue().equals(separateType)) {
            roadSlowLane.setSidewalkWidth(binding.sidewalkWidth.getBigDecimalValue());
            roadSlowLane.setSidewalkPavementType(Enums.PavementTypeEnum.getKeyByValue(binding.sidewalkPavementType.getStringValue()));
            roadSlowLane.setBicycleLaneWidth(binding.bicycleLaneWidth.getBigDecimalValue());
            roadSlowLane.setBicycleLanePavementType(Enums.PavementTypeEnum.getKeyByValue(binding.bicycleLanePavementType.getStringValue()));
            roadSlowLane.setSeparateTypeWidth(binding.separateTypeWidth.getBigDecimalValue());
        }
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void deleteData() {

    }

    private void linkToEditActivity() {
    }

    /**
     * 展示/隐藏下面的LinearLayout
     */
    private void showVIew(String separateTypeName) {
        binding.separateType.setValue(separateTypeName);
        // 展示/隐藏组件
        int roadSeparateTypeKey = Enums.RoadSeparateTypeEnum.getKeyByValue(separateTypeName);
        switch (roadSeparateTypeKey) {
            case 0:
                // 展示人非混行，隐藏标线/物理隔离
                binding.llSlowLane.setVisibility(View.VISIBLE);
                binding.llQuarantine.setVisibility(View.GONE);
                break;
            case 1:
                // 展示标线隔离，隐藏人非混行 物理隔离
                binding.llSlowLane.setVisibility(View.GONE);
                binding.llQuarantine.setVisibility(View.VISIBLE);
                binding.llPhysics.setVisibility(View.GONE);
                break;
            case 2:
                // 展示标线/物理隔离，隐藏人非混行
                binding.llSlowLane.setVisibility(View.GONE);
                binding.llQuarantine.setVisibility(View.VISIBLE);
                binding.llPhysics.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_SLOW_LANE_FILE_BIZ_TYPE);
            }
        }
    }

    // 切换人非分隔形式
    @OnClick({R.id.separateType})
    public void onChangeSeparateType(View view) {
        TextViewUtil.closeKeyboard(this);
        RollUtil.alertBottomWheelOption(this, separateTypeDict, binding.separateType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
            @Override
            public void onClick(View view, int index) {
                // 展示不同的LinearLayout
                showVIew(separateTypeDict.get(index));
            }
        });
    }

    @OnClick({R.id.slowLanePavementType, R.id.sidewalkPavementType, R.id.bicycleLanePavementType})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.slowLanePavementType:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, slowLanePavementTypeDict, binding.slowLanePavementType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.slowLanePavementType.setValue(slowLanePavementTypeDict.get(index));
                    }
                });
                break;
            case R.id.sidewalkPavementType:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, sidewalkPavementTypeDict, binding.sidewalkPavementType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.sidewalkPavementType.setValue(sidewalkPavementTypeDict.get(index));
                    }
                });
                break;
            case R.id.bicycleLanePavementType:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, bicycleLanePavementTypeDict, binding.bicycleLanePavementType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.bicycleLanePavementType.setValue(bicycleLanePavementTypeDict.get(index));
                    }
                });
                break;
        }
    }


}